package com.fzg.common.demo.practice;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * create by fzg
 * 2022/11/4 17:05
 * 等差数列求和
 * 输入三个数：首项，末项，公差
 * 中间空格隔开
 * 求和
 */


public class DengChaSum {

    public static void main(String[] args) {
        System.out.println("请分别输入首项，末项，公差\n用空格隔开: \n");
        Scanner scan = new Scanner(System.in);
        String str_0 = scan.nextLine();
        String[] line_list_0 = str_0.trim().split(" ");
        ArrayList<Integer> arr = new ArrayList<>();


        Pattern pattern = Pattern.compile("[0-9]*");

        for (String s : line_list_0) {
            Matcher isNum = pattern.matcher(s.trim());
            if (!isNum.matches()) {
                System.out.println("输入的内容不合法");
                break;
            } else {
                arr.add(Integer.parseInt(s));
            }
        }
        if (arr.size() != 3){
            System.out.println("没有按照要求输入！");
        }
        scan.close();
        int result = solution(arr);
        System.out.println(result);

    }

    public static int solution(ArrayList<Integer> arr){
        int result;

        // TODO: 请在此编写代码
        // 等差数列前n项和：n*a1+n(n-1)/2  或者 n(a1+an)/2
        // 首先根据通项公式：an = a1 + (n-1) * d 求出 n
        // arr.get(0) 就是 a1
        // arr.get(1) 就是 an
        // arr.get(2) 就是 d
        // (n - 1) * d = an - a1
        // n - 1 = (an - a1) / d
        // n = (an - a1) / d +1
        Integer a1 = arr.get(0);
        Integer an = arr.get(1);
        Integer d = arr.get(2);
        int n = (an - a1) / d + 1;
        result = n * (a1 + an) / 2;
        // result = n * a1 + n * (n - 1) * d / 2;

        return result;
    }

}
